use axum::{
    extract::{Extension, Path},
    http::StatusCode,
    response::Json,
};
use serde_json::Value;
use crate::core::engine::OpsPanelCore;
// 在 core/engine.rs 中扩展状态管理
use std::time::{Duration, Instant};

struct StateEntry {
    value: Value,
    expires_at: Option<Instant>,
}

impl OpsPanelCore {
    pub fn set_state_with_ttl(&self, key: String, value: Value, ttl: Option<Duration>) {
        let entry = StateEntry {
            value,
            expires_at: ttl.map(|d| Instant::now() + d),
        };
        self.state_map.insert(key, entry);
    }

    pub fn get_state(&self, key: &str) -> Option<Value> {
        self.state_map.get(key).and_then(|entry| {
            if let Some(expiry) = entry.expires_at {
                if expiry < Instant::now() {
                    self.state_map.remove(key);
                    return None;
                }
            }
            Some(entry.value.clone())
        })
    }
}


#[derive(serde::Deserialize)]
pub struct SetStateRequest {
    pub key: String,
    pub value: Value,
}

pub async fn get_state_handler(
    Extension(core): Extension<OpsPanelCore>,
    Path(key): Path<String>,
) -> Result<Json<Value>, StatusCode> {
    match core.get_state(&key) {
        Some(value) => Ok(Json(value)),
        None => Err(StatusCode::NOT_FOUND),
    }
}

pub async fn set_state_handler(
    Extension(core): Extension<OpsPanelCore>,
    Json(payload): Json<SetStateRequest>,
) -> Json<()> {
    core.set_state(payload.key, payload.value);
    Json(())
}
